import { Button, Card, Form, Input } from 'antd'
import { useEffect } from 'react'
import './WechatConfig.css'

export default function WechatConfig({ title, items, onChange, onFinish, onFailed }) {
  const [form] = Form.useForm()

  useEffect(() => {
    /** @var result {
      "wx_app_id": "wx25092709236336",
      "wx_app_secret": "1234567890abcdefg",
      "wx_mch_id": "1523894324233",
      "wx_mch_secret": "1830123782934siou233",
      "wx_notify_url": "/api/notify/wechat"
    } */
    if (items && items.length > 0) {
      const result = items.reduce((acc, cur) => ((acc[cur.key] = cur.value), acc), {})
      form.setFieldsValue({ ...result })
    }
  }, [items, form])

  return (
    <div>
      <Card className="panel-wechat-config" type="inner" title={title}>
        <Form
          name="wechat"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFailed}
          autoComplete="off">
          {items.map((item, index) => (
            <Form.Item
              key={item.id}
              label={item.name}
              name={item.key}
              rules={[{ required: true, message: '请输入' + item.name + '!' }]}>
              <Input
                size="large"
                value={item.value}
                onChange={(e) => {
                  onChange((prev) => {
                    const arr = prev.filter((i) => i.id !== item.id)
                    arr.splice(index, 0, { ...prev[index], value: e.target.value })
                    return arr
                  })
                  form.setFieldsValue({ [item.key]: e.target.value })
                }}
              />
              <p style={{ fontSize: 12, color: 'gray', opacity: 0.4 }}>{item.desc}</p>
            </Form.Item>
          ))}

          <Form.Item label={null}>
            <Button
              size="large"
              htmlType="submit"
              className="bg-green-500! text-white! border-green-500! hover:bg-green-500/80! w-full">
              保 存
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
